package org.smartbox.modules.devices.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.smartbox.common.api.vo.Result;
import org.smartbox.common.aspect.annotation.AutoLog;
import org.smartbox.common.system.query.QueryGenerator;
import org.smartbox.common.system.vo.LoginUser;
import org.smartbox.common.util.oConvertUtils;
import org.smartbox.modules.devices.bean.DevCounts;
import org.smartbox.modules.devices.entity.DevBasicInfo;
import org.smartbox.modules.devices.entity.DevBoardInfo;
import org.smartbox.modules.devices.entity.DevChassisInfo;
import org.smartbox.modules.devices.entity.DevDevices;
import org.smartbox.modules.devices.entity.DevDevicesItem;
import org.smartbox.modules.devices.entity.DevInterfaceInfo;
import org.smartbox.modules.devices.entity.DevSubboardInfo;
import org.smartbox.modules.devices.service.IDevBoardInfoService;
import org.smartbox.modules.devices.service.IDevChassisInfoService;
import org.smartbox.modules.devices.service.IDevDevicesItemService;
import org.smartbox.modules.devices.service.IDevDevicesService;
import org.smartbox.modules.devices.service.IDevInfoManageService;
import org.smartbox.modules.devices.service.IDevInterfaceInfoService;
import org.smartbox.modules.devices.service.IDevSubboardInfoService;
import org.smartbox.modules.system.model.TreeSelectModel;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 设备列表相关
 * @Author: suibin
 * @Date:   2019-05-29
 * @Version: V1.0
 */
@RestController
@RequestMapping("/dev/devices")
@Slf4j
@Api(tags="设备管理")
public class DevDevicesController {
	@Autowired
	private IDevDevicesService devDevicesService;
	
	@Autowired
	private IDevInfoManageService  devInfoManageService;
	
	@Autowired
	private IDevDevicesItemService devDevicesItemService;	

	@Autowired
	private IDevInterfaceInfoService devInterfaceInfoService;	

	@Autowired
	private IDevBoardInfoService devBoardInfoService;	
	
	@Autowired
	private IDevChassisInfoService devChassisInfoService;		
	
	@Autowired
	private IDevSubboardInfoService devSubboardInfoService;			
	
	/**
	  * 分页列表查询
	 * @param sysCategory
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/rootList")
	public Result<IPage<DevBasicInfo>> queryPageList(DevBasicInfo devDevices,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		//if(oConvertUtils.isEmpty(devDevices.get.getPid())){
		//	sysCategory.setPid("0");
		//}
		Result<IPage<DevBasicInfo>> result = new Result<IPage<DevBasicInfo>>();
		
		//--author:os_chengtgen---date:20190804 -----for: 分类字典页面显示错误,issues:377--------start
		//QueryWrapper<SysCategory> queryWrapper = QueryGenerator.initQueryWrapper(sysCategory, req.getParameterMap());
		QueryWrapper<DevBasicInfo> queryWrapper = new QueryWrapper<DevBasicInfo>();
		//queryWrapper.eq("pid", 0);
		//--author:os_chengtgen---date:20190804 -----for: 分类字典页面显示错误,issues:377--------end
		
		Page<DevBasicInfo> page = new Page<DevBasicInfo>(pageNo, pageSize);
		IPage<DevBasicInfo> pageList = devInfoManageService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	@GetMapping(value = "/childList")
	public Result<List<DevDevicesItem>> queryPageList(DevDevices devDevices,HttpServletRequest req) {
		Result<List<DevDevicesItem>> result = new Result<List<DevDevicesItem>>();
		//QueryWrapper<DevDevices> queryWrapper = QueryGenerator.initQueryWrapper(devDevices, req.getParameterMap());
		List<DevDevicesItem> list = devDevicesItemService.selectItemsByMainId(devDevices.getId());
		result.setSuccess(true);
		result.setResult(list);
		return result;
	}
	
	
	
	
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<DevDevices> delete(@RequestParam(name="id",required=true) String id) {
		Result<DevDevices> result = new Result<DevDevices>();
		DevDevices ob = devDevicesService.getById(id);
		if(ob==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = devDevicesService.removeById(id);
			if(ok) {
				result.success("删除成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<DevDevices> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<DevDevices> result = new Result<DevDevices>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.devDevicesService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<DevDevices> queryById(@RequestParam(name="id",required=true) String id) {
		Result<DevDevices> result = new Result<DevDevices>();
		DevDevices ob = devDevicesService.getById(id);
		if(ob==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(ob);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, DevDevices devDevices) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<DevDevices> queryWrapper = QueryGenerator.initQueryWrapper(devDevices, request.getParameterMap());
      List<DevDevices> pageList = devDevicesService.list(queryWrapper);
      // Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      // 过滤选中数据
      String selections = request.getParameter("selections");
      if(oConvertUtils.isEmpty(selections)) {
    	  mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      }else {
    	  List<String> selectionList = Arrays.asList(selections.split(","));
    	  List<DevDevices> exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
    	  mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
      }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "分类字典列表");
      mv.addObject(NormalExcelConstants.CLASS, DevDevices.class);
      LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("分类字典列表数据", "导出人:"+user.getRealname(), "导出信息"));
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<DevDevices> listSysCategorys = ExcelImportUtil.importExcel(file.getInputStream(), DevDevices.class, params);
              for (DevDevices sysCategoryExcel : listSysCategorys) {
            	  devDevicesService.save(sysCategoryExcel);
              }
              return Result.ok("文件导入成功！数据行数:" + listSysCategorys.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }
  
  
  
  /**
     * 加载单个数据 用于回显
   */
    @RequestMapping(value = "/loadOne", method = RequestMethod.GET)
 	public Result<DevDevices> loadOne(@RequestParam(name="field") String field,@RequestParam(name="val") String val) {
 		Result<DevDevices> result = new Result<DevDevices>();
 		try {
 			
 			QueryWrapper<DevDevices> query = new QueryWrapper<DevDevices>();
 			query.eq(field, val);
 			List<DevDevices> ls = this.devDevicesService.list(query);
 			if(ls==null || ls.size()==0) {
 				result.setMessage("查询无果");
 	 			result.setSuccess(false);
 			}else if(ls.size()>1) {
 				result.setMessage("查询数据异常,["+field+"]存在多个值:"+val);
 	 			result.setSuccess(false);
 			}else {
 				result.setSuccess(true);
 				result.setResult(ls.get(0));
 			}
 		} catch (Exception e) {
 			e.printStackTrace();
 			result.setMessage(e.getMessage());
 			result.setSuccess(false);
 		}
 		return result;
 	}
   
    /**
          * 加载节点的子数据
     */
    @RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
	public Result<List<TreeSelectModel>> loadTreeChildren(@RequestParam(name="pid") String pid) {
		Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
		try {
			List<TreeSelectModel> ls = this.devDevicesService.queryListByPid(pid);
			result.setResult(ls);
			result.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMessage(e.getMessage());
			result.setSuccess(false);
		}
		return result;
	}
    
    /**
         * 加载一级节点/如果是同步 则所有数据
     */
    @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
   	public Result<List<TreeSelectModel>> loadTreeRoot(@RequestParam(name="async") Boolean async,@RequestParam(name="pcode") String pcode) {
   		Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
   		try {
   			List<TreeSelectModel> ls = this.devDevicesService.queryListByCode(pcode);
   			if(!async) {
   				loadAllCategoryChildren(ls);
   			}
   			result.setResult(ls);
   			result.setSuccess(true);
   		} catch (Exception e) {
   			e.printStackTrace();
   			result.setMessage(e.getMessage());
   			result.setSuccess(false);
   		}
   		return result;
   	}
  
    /**
         * 递归求子节点 同步加载用到
     */
  	private void loadAllCategoryChildren(List<TreeSelectModel> ls) {
  		for (TreeSelectModel tsm : ls) {
			List<TreeSelectModel> temp = this.devDevicesService.queryListByPid(tsm.getKey());
			if(temp!=null && temp.size()>0) {
				tsm.setChildren(temp);
				loadAllCategoryChildren(temp);
			}
		}
  	}

  	
	/**
	 * 获取某用户下设备报表信息
	 * @return
	 */
	@ApiOperation("获取某用户下设备报表数量")
	@GetMapping("reportFormCount")
	public Result<List<Map<String,Object>>> reportFormCount(@RequestParam(name="uid", required = true) String uid) {
		Result<List<Map<String,Object>>> result = new Result<List<Map<String,Object>>>();
		//JSONObject obj = new JSONObject();
		//update-begin--Author:zhangweijian  Date:20190428 for：传入开始时间，结束时间参数
		// 获取一天的开始和结束时间
		Calendar calendar = new GregorianCalendar();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		Date dayStart = calendar.getTime();
		calendar.add(Calendar.DATE, 1);
		Date dayEnd = calendar.getTime();
		// 获取该用户的状态数量
		List<Map<String,Object>> totalVisitCount = devInfoManageService.getDevCountsByUid(uid);

		result.setResult(totalVisitCount);
		result.success("ok");
		return result;
	}
	
	/**
	  * 分页列表查询
	 * @param devInterfaceInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "设备接口相关-分页列表查询")
	@ApiOperation(value="设备接口相关-分页列表查询", notes="设备接口相关-分页列表查询")
	@GetMapping(value = "/interfacelist")
	public Result<IPage<DevInterfaceInfo>> queryPageList(DevInterfaceInfo devInterfaceInfo,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="50") Integer pageSize,
									  @RequestParam(name = "uid", required = true) String uid,
									  @RequestParam(name = "devid", required = true) String devid,
									  HttpServletRequest req) {
		Result<IPage<DevInterfaceInfo>> result = new Result<IPage<DevInterfaceInfo>>();

		Page<DevInterfaceInfo> page = new Page<DevInterfaceInfo>(pageNo, pageSize);
		IPage<DevInterfaceInfo> pageList = devInterfaceInfoService.selectUserPage(page, uid, devid);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	

	/**
	  * 分页列表查询
	 * @param devInterfaceInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "单板列表-分页列表查询")
	@ApiOperation(value="单板列表-分页列表查询", notes="单板列表-分页列表查询")
	@GetMapping(value = "/boardInfolist")
	public Result<IPage<DevBoardInfo>> boardInfolist(DevBoardInfo devBoardInfo,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="50") Integer pageSize,
									  @RequestParam(name = "uid", required = true) String uid,
									  @RequestParam(name = "devid", required = true) String devid,
									  HttpServletRequest req) {
		Result<IPage<DevBoardInfo>> result = new Result<IPage<DevBoardInfo>>();

		Page<DevBoardInfo> page = new Page<DevBoardInfo>(pageNo, pageSize);
		IPage<DevBoardInfo> pageList = devBoardInfoService.selectUserPage(page, uid, devid);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  * 分页列表查询
	 * @param devInterfaceInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "机框-分页列表查询")
	@ApiOperation(value="机框-分页列表查询", notes="机框-分页列表查询")
	@GetMapping(value = "/chassisInfolist")
	public Result<IPage<DevChassisInfo>> chassisInfolist(DevChassisInfo devInterfaceInfo,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="50") Integer pageSize,
									  @RequestParam(name = "uid", required = true) String uid,
									  @RequestParam(name = "devid", required = true) String devid,
									  HttpServletRequest req) {
		Result<IPage<DevChassisInfo>> result = new Result<IPage<DevChassisInfo>>();

		Page<DevChassisInfo> page = new Page<DevChassisInfo>(pageNo, pageSize);
		IPage<DevChassisInfo> pageList = devChassisInfoService.selectUserPage(page, uid, devid);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}	
	
	/**
	  * 分页列表查询
	 * @param devInterfaceInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "子卡-分页列表查询")
	@ApiOperation(value="子卡-分页列表查询", notes="子卡-分页列表查询")
	@GetMapping(value = "/suboardInfolist")
	public Result<IPage<DevSubboardInfo>> suboardInfolist(DevSubboardInfo devInterfaceInfo,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="50") Integer pageSize,
									  @RequestParam(name = "uid", required = true) String uid,
									  @RequestParam(name = "devid", required = true) String devid,
									  HttpServletRequest req) {
		Result<IPage<DevSubboardInfo>> result = new Result<IPage<DevSubboardInfo>>();

		Page<DevSubboardInfo> page = new Page<DevSubboardInfo>(pageNo, pageSize);
		IPage<DevSubboardInfo> pageList = devSubboardInfoService.selectUserPage(page, uid, devid);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}		
	
	@AutoLog(value = "子卡-分页列表查询")
	@ApiOperation(value="子卡-分页列表查询", notes="子卡-分页列表查询")
	@GetMapping(value = "/suboardlistByBid")
	public Result<IPage<DevSubboardInfo>> suboardlistByBid(DevSubboardInfo devInterfaceInfo,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="50") Integer pageSize,
									  @RequestParam(name = "uid", required = true) String uid,
									  @RequestParam(name = "boardid", required = true) String boardid,
									  HttpServletRequest req) {
		Result<IPage<DevSubboardInfo>> result = new Result<IPage<DevSubboardInfo>>();

		Page<DevSubboardInfo> page = new Page<DevSubboardInfo>(pageNo, pageSize);
		IPage<DevSubboardInfo> pageList = devSubboardInfoService.selectSubPageByBid(page, uid, boardid);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}	
	
	
}
